package series;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class SeriesDAO {

	@Autowired
	private JdbcTemplate db;

	@Autowired
	private SeasonDAO seasonDAO;
	
	private static final class SeriesRowMapper implements
			ParameterizedRowMapper<Serie> {

		@Override
		public Serie mapRow(ResultSet rs, int rowNum) throws SQLException {
			Serie entry = new Serie(rs.getInt(1), rs.getString(2));
			return entry;
		}
	}


	public SeriesDAO() {
		super();
	}

	public SeriesDAO(JdbcTemplate jdbc, SeasonDAO seasonDAO) {
		this.db = jdbc;
		this.seasonDAO = seasonDAO;
	}

	public JdbcTemplate getJdbcTemplate() {
		return db;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.db = jdbcTemplate;
	}

	public Series watching() {
		Series series = new Series();

		String sql = "select * from series";
		List<Serie> entries = db.query(sql, new SeriesRowMapper());
		for (Serie serie : entries) {
			Season[] seasonsForSeries = seasonDAO.seasonsForSeries(seriesId(serie.getName()));
			serie.addSeasons(seasonsForSeries);
			series.add(serie);
		}
		return series;
	}

	public int seriesId(String seriesName) {
		String seriesIdSQL = "select id from series where name='" + seriesName + "'";
		Integer seriesId = db.queryForInt(seriesIdSQL);
		return seriesId;
	}

	public String seriesName() {
		String seriesIdSQL = "select name from episodes where id=1";
		String seriesId = db.queryForObject(seriesIdSQL,String.class);
		return seriesId;
	}
}
